package com.xinyue.cross.server.client;


import com.xinyue.cross.server.client.model.NettyConnectionCloseEvent;
import com.xinyue.game.message.GameServerMessageModel;
import com.xinyue.game.message.GameServerRequestHeader;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class NettyClientService {
    private static Logger logger = LoggerFactory.getLogger(NettyClientService.class);
    private String host;
    private int port;

    private Channel channel;
    private Bootstrap bootstrap;
    private EventLoopGroup group = new NioEventLoopGroup(2);

    public NettyClientService(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public void connect(ApplicationContext context) throws InterruptedException {
        bootstrap = new Bootstrap();
        this.channel = bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new IdleStateHandler(0, 0, 60));
                        ch.pipeline().addLast(new MessageEncodeHandler());
                        ch.pipeline().addLast(new MessageDecodeHandler());
                        ch.pipeline().addLast(new ServerMessageHandler(context));
                    }
                })
                .connect(host, port).sync().channel();
        channel.closeFuture().addListener(future -> {
            this.close(context);
        });
        logger.info("服务客户端连接服务成功，host: {},port: {}", host, port);
    }

    public void close(ApplicationContext context) {
        NettyConnectionCloseEvent event = new NettyConnectionCloseEvent(this, channel);
        context.publishEvent(event);
    }

    public boolean isConnected() {
        return this.channel != null && this.channel.isActive();
    }

    public Channel getChannel() {
        return channel;
    }

    public void sendMessage(GameServerMessageModel<GameServerRequestHeader> messageModel) {
        this.channel.writeAndFlush(messageModel);
    }
}
